package net.alan.modules.wx;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.stereotype.Component;

import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.util.Set;
import java.util.concurrent.CopyOnWriteArraySet;

/**
 * Author 李岩飞
 * Email eliyanfei@126.com
 * 2017/12/20
 */
@Component
@ServerEndpoint("/webSocket/{id}")
public class WebSocket {
    public static Set<WebSocket> webSockets = new CopyOnWriteArraySet();
    public MessageVO messageVO = new MessageVO();
    public Session session;
    public Integer userId;

    @OnOpen
    public void onOpen(@PathParam("id") Integer id, Session session) {
        this.userId = id;
        this.session = session;
        webSockets.add(this);
        System.out.println("【websocket消息】有新的连接, 总数:{}" + webSockets.size());
    }


    @OnClose
    public void onClose() {
        webSockets.remove(this);
        System.out.println("【websocket消息】连接断开, 总数:{}" + webSockets.size());
    }

    @OnMessage
    public void onMessage(String message, Session session) {
        messageVO.setContent(message);
        ObjectMapper mapper = new ObjectMapper();
        String Json = "";
        try {
            Json = mapper.writeValueAsString(messageVO);
        } catch (Exception ex) {
        }
        this.sendMessage(Json);
        System.out.println("【websocket消息】收到客户端发来的消息:{}" + message);
    }

    public void sendMessage(String message) {
        for (WebSocket webSocket : webSockets) {
            System.out.println("【websocket消息】广播消息, message={}" + message);
            try {
                webSocket.session.getBasicRemote().sendText(message);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}